import java.nio.ByteBuffer;
import java.util.Enumeration;
import java.util.zip.GZIPInputStream;

import java.io.*;
import org.xlightweb.client.*;

import org.xsocket.Execution;
import org.xlightweb.*;


public class LearnxLightWeb {
	
	
	public static void main(String[] args) throws Exception{
		
		LearnxLightWeb lweb = new LearnxLightWeb();
		//lweb.useBlockWay();
		
		//lweb.useNonBlockWay();
		
		
		//lweb.useBlockHttpClient();
		lweb.useHttpClient();
		
	}
	
	public void useNonBlockWay()throws Exception{
		IHttpClientEndpoint httpClientConnection = new HttpClientConnection("www.sina.com", 80);
		IHttpRequest request = new GetRequest("www.sina.com");

		request.setHeader("Accept-Encoding", "gzip,deflate");
		IHttpResponse response = httpClientConnection.call(request);
		String contentType = response.getContentType();
		System.out.println(contentType);
		NonBlockingBodyDataSource  bodyDataSource = response.getNonBlockingBody();
		
		
		IBodyDataHandler bodyHandler = new BodyHandler();
		response.getNonBlockingBody().setDataHandler(bodyHandler); 
		
		}
		
		
		
	public void useBlockWay()throws Exception{
		
		IHttpClientEndpoint httpClientConnection = new HttpClientConnection("192.168.12.52", 3688);
		IHttpRequest request = new GetRequest("http://192.168.12.52:3688/spamfilter/service-stat");

		// add request header data
		request.setHeader("Accept-Encoding", "gzip,deflate");
		
		// perform the request
		IHttpResponse response = httpClientConnection.call(request);
		        
		// get repsonse header data 
		String contentType = response.getContentType();
		System.out.println(contentType);
		
		
		BlockingBodyDataSource bodyDataSource = response.getBlockingBody();
		//String data = bodyDataSource.readString("utf-8");//???
		byte[] bb = bodyDataSource.readBytes();
		
		String data = new String(bb,"utf-8");
		System.out.println(data);

	}
	public void useBlockHttpClient()throws Exception{
		
		HttpClient httpClient = new HttpClient();
		// set some properties
	    httpClient.setFollowsRedirect(true);  
	    httpClient.setAutoHandleCookies(false);
	   	httpClient.setResponseBodyDefaultEncoding("gbk");
	   	httpClient.addInterceptor(new HeaderLogFilter());
	   	
		IHttpRequest request = new GetRequest("http://www.sohu.com");
		
		//request.setHeader("Accept-Encoding", "gzip,deflate");
		HttpResponse response = (HttpResponse)httpClient.call(request);
		System.out.println("-------------------call request over----------------");
		System.out.println(response.getResponseHeader());
		BlockingBodyDataSource	bodyDataSource = response.getBlockingBody() ;
		String data = bodyDataSource.readString();//???
		System.out.println("-------------------get response over----------------");
		//byte[] bb = bodyDataSource.readBytes();
		//String data = new String(bb,"utf-8");
		System.out.println(data);
		httpClient.close();
	}
	
	public void useHttpClient()throws Exception{
		
		HttpClient httpClient = new HttpClient();
	    httpClient.setFollowsRedirect(true);  
	    httpClient.setAutoHandleCookies(false);
	   	httpClient.setResponseBodyDefaultEncoding("gbk");
		IHttpRequest request = new GetRequest("http://www.sohu.com");
		
		request.setHeader("Accept-Encoding", "gzip,deflate");
		System.out.println("-------------------send request----------------");
		//IFutureResponse futureResponse = httpClient.send(request);
		httpClient.send(request, new MyResponseHandler());
		System.out.println("-------------------send over----------------");
		
		try{
			Thread.sleep(3000);
		} catch (Exception ex) {}
		
		httpClient.close();
	}
}


@Execution(Execution.MULTITHREADED)
class MyResponseHandler implements IHttpResponseHandler {

	@InvokeOn(InvokeOn.MESSAGE_RECEIVED)
     public void onResponse(IHttpResponse response) throws IOException {
        System.out.println("-------------------Handler onResponse----------------");
        System.out.println(response.getResponseHeader());
        BlockingBodyDataSource	bodyDataSource = response.getBlockingBody() ;
        String cth = response.getHeader("Content-Encoding");
		System.out.println(cth);
		String data = null;
        if(cth != null && cth.indexOf("gzip") != -1){
	      BufferedReader brd = new BufferedReader(
	          new InputStreamReader(
	            new GZIPInputStream(
	              new ByteArrayInputStream(bodyDataSource.readBytes())),"gbk" ));
        	while((data = brd.readLine()) != null)
        	System.out.println(data);

        }else{
        	data = bodyDataSource.readString();
        	System.out.println(data);
        }
        
     }

     public void onException(IOException ioe) {
        System.out.println("error occured by receiving response " + ioe.toString());
     }
}

      
class HeaderLogFilter implements IHttpRequestHandler {
	
	@InvokeOn(InvokeOn.MESSAGE_RECEIVED)
   public void onRequest(final IHttpExchange exchange) throws IOException {

      // print out request header
      System.out.println("-------------------intercepter onRequest----------------"); 
      System.out.println(exchange.getRequest().getRequestHeader());
 

      IHttpResponseHandler respHdl = new IHttpResponseHandler() {

         public void onResponse(IHttpResponse response) throws IOException {
            // print out response header
            System.out.println("-------------------intercepter onResponse----------------");
            System.out.println(response.getResponseHeader());
            
            exchange.send(response);
        }

         public void onException(IOException ioe) {
            System.out.println("error occured by receiving response " + ioe.toString());
            exchange.sendError(500);
         }
      };

      //exchange.forward(exchange.getRequest(), respHdl);
	  exchange.forward(exchange.getRequest());
   }
}  

class BodyHandler implements IBodyDataHandler {
	
	
	ByteBuffer bb = null;
	
	BodyHandler(){
		bb = ByteBuffer.allocate(1024);	
	}
	
	public boolean onData(NonBlockingBodyDataSource  nbd){
		System.out.println("get data now !");
		try{
			int avnum = nbd.available();
			System.out.println("get length : " + avnum);
			if (avnum > 0 ){
				
				nbd.read(bb);
			}	else if (avnum == -1){ //???
				String content = new String(bb.array(), "gbk");
				System.out.println(content);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} 

		
		return true;
	}
}